package com.test.fundible.fundible_00_utils;

import static com.test.fundible.fundible_00_utils.FundibleConfigs.*;
import static com.test.fundible.fundible_04_home.PersonalCenterF_fundibleragment.HeadBm;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.test.fundible.fundible_01_launcher.Base_fundibleApplication;
import com.test.fundible.fundible_10_vip.Pers_fundibleonalIn_fundiblefo;
import com.test.fundible.fundible_00_path.Paths_fundible;

import org.jetbrains.annotations.NotNull;

import java.nio.charset.StandardCharsets;
import android.os.Handler;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class FundibleUtil {

    private static Loading_fundibleDialog LoadDialog;
    private static final Handler Handler = new Handler(Looper.getMainLooper());

    public static void fundibleRun(Runnable runnable,int i){
        if (i>0) runnable.run();
        else fundibleRun(runnable);
    }

    private static void fundibleRun(Runnable runnable){
        runnable.run();
    }

    //启动初始化
    public static void fundibleInit(Context context){

        //在主线程初始化
        initSharedPreferences();

        //在子线程初始化
//        new Thread(() -> {
//
//
//
//        }).start();

    }


//----------------------AES加解密----------------------------

    //加密
    public static String encryptDefault_fundible(String msg) {

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(
                    Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES"),
                    new IvParameterSpec(AES_IV.getBytes(StandardCharsets.UTF_8))
            );

            //tag2024
            String result = Base64.encodeToString(cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT | Base64.NO_WRAP);
            Log.w("---encrypt_src---", msg );
            Log.w("---encrypt---", result );
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    //解密
    public static String decryptDefault_fundible(String encryptedMessage) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            cipher.init(
                    Cipher.DECRYPT_MODE,
                    new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES"),
                    new IvParameterSpec(AES_IV.getBytes(StandardCharsets.UTF_8))
            );

            //tag2024
            String result =  new String(cipher.doFinal(Base64.decode(encryptedMessage, Base64.DEFAULT | Base64.NO_WRAP)), StandardCharsets.UTF_8);
            Log.w("---decrypt_src---", encryptedMessage );
            Log.w("---decrypt---", result );
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

//-----------------------------------国家配置----------------------------

    public static String front;
    public static String areaCode;


    public static String getFront_fundible() {
        if (TextUtils.isEmpty(front)) return "";
        return front;
    }

    public static boolean isFrontEmpty_fundible(){
        return TextUtils.isEmpty(front) || front.length()<=1;
    }

    public static void setFront_fundible(String front) {
        FundibleUtil.front = "/"+ front;
    }

    public static String getCommonPath_fundible(){
        if (TextUtils.isEmpty(front)) return "";
        return Paths_fundible.BasePath + getFront_fundible()+ Paths_fundible.CommonPath;
    }

    public static void setAreaCode_fundible(String areaCode) {
        FundibleUtil.areaCode = areaCode;
        mSharedPreferences_fundible.edit().putString(SP_KE_fundibleY_AREACODE, FundibleUtil.areaCode).apply();
    }

    public static String getAreaCode_fundible() {
        if (TextUtils.isEmpty(areaCode)) return "";
        if (areaCode.startsWith("+")) return areaCode;
        return "+"+areaCode;
    }

    public static boolean isGhana_fundible(){
        return Are_fundibleaCode_Ghana.endsWith(getAreaCode_fundible());
    }

    public static boolean isCote_fundible(){
        return AreaCo_fundiblede_Cote.endsWith(getAreaCode_fundible());
    }

    public static boolean isUganda_fundible(){
        return Are_fundibleaCode_Uganda.endsWith(getAreaCode_fundible());
    }

    public static boolean isCameroon_fundible(){
        return AreaC_fundibleode_Cameroon.endsWith(getAreaCode_fundible());
    }

    public static boolean isZambia_fundible(){
        return Area_fundibleCode_Zambia.endsWith(getAreaCode_fundible());
    }

    public static boolean isSenegal_fundible(){
        return Are_fundibleaCode_Senegal.endsWith(getAreaCode_fundible());
    }

    public static boolean isTanzan_fundible(){
        return AreaC_fundibleode_Tanzan.endsWith(getAreaCode_fundible());
    }

    public static boolean isEnglish_fundible(){
        return isGhana_fundible()|| isUganda_fundible()|| isZambia_fundible();
    }

    public static boolean isFrench_fundible(){
        return isCote_fundible()|| isCameroon_fundible()|| isSenegal_fundible();
    }

    public static boolean isGetOrderRepayH5_fundible(){
        return isUganda_fundible();
    }

    public static boolean isOrderRepayH5_fundible(){
        return !isGetOrderRepayH5_fundible();
    }

//-------------------------权限--------------------------

    public static boolean checkAllPermission_fundible(Context context){
        for (String permission: Permiss_fundibleions_All){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,permission)) return false;
        }
        return true;
    }

    public static boolean checkStartPermission_fundible(Context context){
        for (String permission: Perm_fundibleissions_Start){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,permission)) return false;
        }
        return true;
    }

    public static boolean checkPermissions_fundible(Context context, String... permissions){
        for (String permission:permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,permission)) return false;
        }
        return true;
    }

    public static boolean checkCameraPermission_fundible(Context context){
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, Permission_CAMERA);
    }

    public static boolean checkPhonestatePermission_fundible(Context context){
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, Permission_PHONE_STATE);
    }

//------------------------------用户贷款状态--------------------------

    public static String State_fundible = "No_State";

    public static boolean isStateChange_fundible(String newState){
        if (newState.equalsIgnoreCase(State_fundible)) return false;

        //状态：还款 -> 无订单  经验+10
        if (State_fundible.equalsIgnoreCase(State_R_fundiblep) && newState.equalsIgnoreCase(State_NoO_fundiblerder)){
            Pers_fundibleonalIn_fundiblefo.getInstance().addExpValue(10);
            Pers_fundibleonalIn_fundiblefo.getInstance().uploadUserInfo(null);
        }

        State_fundible = newState;
        return true;
    }

    public static void clearState_fundible(){
        State_fundible = "No_State";
    }

//---------------------------------------本地存储-----------------------------

    public static SharedPreferences mSharedPreferences_fundible;

    /**
     * 登录手机号
     */
    public static String mMobile_fundible;
    /**
     * 登录token
     */
    public static String mToken_fundible;
    /**
     * 登录user_id
     */
    public static String mUserId_fundible;
    /**
     * 是否为渠道用户
     */
    public static boolean isAdSource_fundible;

    public static int normaldialogCount_fundible;
    public static int activedialogCount_fundible;


    public static void initSharedPreferences(){

        mSharedPreferences_fundible = Base_fundibleApplication.getInstant().getSharedPreferences(getPackageName_fundible(), Context.MODE_PRIVATE);
        FundibleUtil.mMobile_fundible = mSharedPreferences_fundible.getString(S_fundibleP_KEY_MOBILE, "");
        FundibleUtil.mToken_fundible = mSharedPreferences_fundible.getString(SP_KEY_TOK_fundibleEN, "");
        FundibleUtil.mUserId_fundible = mSharedPreferences_fundible.getString(SP_KEY_USER_fundibleID, "");
        FundibleUtil.isAdSource_fundible = mSharedPreferences_fundible.getBoolean(SP_KEY_ISA_fundibleDSOURCE,false);
        FundibleUtil.areaCode = mSharedPreferences_fundible.getString(SP_KE_fundibleY_AREACODE,"");
        normaldialogCount_fundible = mSharedPreferences_fundible.getInt(SP_KEY_NORMAL_fundibleDIALOG_COUNT,0);
        activedialogCount_fundible = mSharedPreferences_fundible.getInt(SP_KEY_ACTIVEDI_fundibleALOG_COUNT,0);

    }

    //判断是否已经登录
    public static boolean didLogin_fundible() {
        return !TextUtils.isEmpty(FundibleUtil.mToken_fundible);
    }

    public static String getMobile_fundible() {
        if (TextUtils.isEmpty(mMobile_fundible)) mMobile_fundible ="";
        return mMobile_fundible;
    }

    public static String getEncryptedMobile(){
        if (TextUtils.isEmpty(mMobile_fundible) || mMobile_fundible.length()<6) return "***";
        int length = mMobile_fundible.length();
        return "***"+mMobile_fundible.substring(length-4,length);
    }

    public static String getEncryptMobile_fundible(){
        if (TextUtils.isEmpty(mMobile_fundible)) mMobile_fundible ="";
        int length = mMobile_fundible.length();
        return "***"+ mMobile_fundible.substring(length-4,length);
    }

    @SuppressLint("ApplySharedPref")
    public static void setMobile_fundible(String mobile) {
        FundibleUtil.mMobile_fundible = mobile;
        mSharedPreferences_fundible.edit().putString(S_fundibleP_KEY_MOBILE, FundibleUtil.mMobile_fundible).commit();
    }

    public static String getToken_fundible() {
        if (TextUtils.isEmpty(mToken_fundible)) mToken_fundible = "";
        return mToken_fundible;
    }

    public static String getUserId_fundible() {
        if (TextUtils.isEmpty(mUserId_fundible)) mUserId_fundible = "";
        return mUserId_fundible;
    }

    @SuppressLint("ApplySharedPref")
    public static void setToken_fundible(String token) {
        FundibleUtil.mToken_fundible = token;
        mSharedPreferences_fundible.edit().putString(SP_KEY_TOK_fundibleEN, FundibleUtil.mToken_fundible).commit();
    }

    @SuppressLint("ApplySharedPref")
    public static void setUserId_fundible(String userId) {
        FundibleUtil.mUserId_fundible = userId;
        mSharedPreferences_fundible.edit().putString(SP_KEY_USER_fundibleID, FundibleUtil.mUserId_fundible).commit();
    }

    public static boolean getIsAdSource_fundible(){
        //tag2024
        return true;
//        return isAdSource;
    }

    @SuppressLint("ApplySharedPref")
    public static void setIsAdSource_fundible(boolean isAdSource){
        FundibleUtil.isAdSource_fundible = isAdSource;
        mSharedPreferences_fundible.edit().putBoolean(SP_KEY_ISA_fundibleDSOURCE,isAdSource).commit();
    }

    public static int getNormaldialogCount_fundible() {
        return normaldialogCount_fundible;
    }

    public static int getActivedialogCount_fundible() {
        return activedialogCount_fundible;
    }

    @SuppressLint("ApplySharedPref")
    public static void addNormaldialogCount_fundible(){
        normaldialogCount_fundible++;
        mSharedPreferences_fundible.edit().putInt(SP_KEY_NORMAL_fundibleDIALOG_COUNT, normaldialogCount_fundible).commit();
    }

    @SuppressLint("ApplySharedPref")
    public static void addActivedialogCount_fundible(){
        activedialogCount_fundible++;
        mSharedPreferences_fundible.edit().putInt(SP_KEY_ACTIVEDI_fundibleALOG_COUNT, activedialogCount_fundible).commit();
    }

    public static void clear_fundible(){
        setMobile_fundible("");
        setUserId_fundible("");
        setToken_fundible("");
        HeadBm = null;
    }



//------------------------------工具方法-----------------------------

    @NotNull
    public static String getPackageName_fundible() {
        String pckName = Base_fundibleApplication.getInstant().getPackageName();
        if (TextUtils.isEmpty(pckName)) {
            pckName = FundibleConfigs.PACK_fundibleAGE_NAME;
        }
        return pckName;
    }

    @NotNull
    public String getAndroidID_fundible() {
        String androidID = Settings.System.getString(Base_fundibleApplication.getInstant().getContentResolver(), Settings.Secure.ANDROID_ID);
        if (TextUtils.isEmpty(androidID)) {
            return System.currentTimeMillis() + "";
        }
        if (androidID.contains("00000000")) {
            return System.currentTimeMillis() + "";
        }
        return androidID;
    }


    public static Bitmap getCircleBitmap(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final Paint paint = new Paint();
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);

        // 绘制圆形边框
        canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);

        // 使用SRC_IN模式，保留原图像与遮罩交集的部分
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rectF, paint);

        return output;
    }


    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.heightPixels;
    }

    public static int dpToPx(Context context,float dpValue){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int pxToDp(Context context,float pxValue){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static void safeRun(Runnable runnable){
        if (runnable == null) return;
        if (Looper.myLooper() == Looper.getMainLooper()) runnable.run();
        else Handler.post(runnable);
    }

    public static void startLoading(Context context,String text){
        if (context == null || (LoadDialog!=null&&LoadDialog.isShowing())) return;
        safeRun(() -> {
            LoadDialog = new Loading_fundibleDialog(context);
            LoadDialog.show(text);
        });
    }

    public static void stopLoading(){
        if (LoadDialog == null) return;
        safeRun(() -> {
            if (LoadDialog != null && LoadDialog.isShowing()) LoadDialog.dismiss();
            LoadDialog = null;
        });
    }



}
